import { _decorator, Component, Node, UITransform, Vec3, Animation, tween, Sprite, Widget, Button, game, Font, AudioClip, EventHandler, UIOpacity, } from 'cc';
import { createUILabel, createUINode, getFrameAllAsset, getFrameAsset, loadJosnAndSpriteFrame, setListTrantion } from '../utils';
import DataManager from '../Runtime/DataManager';
import ResourceManager from '../Runtime/ResourceManager';
const { ccclass } = _decorator;
const wx = window['wx']
@ccclass('ControllerManager')
export class ControllerManager extends Component {
    openDrawerName: string = ""
    parentNode: Node = null
    async init() {
        const node = createUINode("controller")
        node.setParent(this.node)
        const transform = node.getComponent(UITransform)
        transform.setContentSize(1280, 1024)
    }
    close(eventData) {
        if (this.openDrawerName == eventData) {
            this.openDrawerName = ""
            this.parentNode = null
        }
        let node = this.node.getChildByName(eventData)
        if (!node || !node.isValid) {
            node = DataManager.Instance.operationNode.getChildByName(eventData)
        }
        if (!node || !node.isValid) {
            return
        }
        if (game.isPaused()) {
            game.resume()
        }
        return new Promise<void>((resolve, reject) => {
            let maskBox = node.getChildByName("maskBox")
            let time = .2
            if (DataManager.Instance.drawerNumber > 1) {
                time = 0
            }
            tween(maskBox)
                .by(time, { position: new Vec3(0, -600, 0) })
                .call(() => {
                    node.destroy();
                    resolve()
                    if (DataManager.Instance.drawerNumber > 0) {
                        DataManager.Instance.drawerNumber = DataManager.Instance.drawerNumber - 1
                    }
                    DataManager.Instance.disbledButton = false
                })
                .start()
        })
    }
    closeDrawer(event: Event, eventData: string) {
        this.close(eventData)
    }
    async loadAssortAssets(close: Boolean = true) {
        let loading = this.getAssetsLength()
        if (!loading) return
        return new Promise<void>(async (resolve, reject) => {
            let data = DataManager.Instance
            let resource = ResourceManager.Instance
            data.homeAssets = await loadJosnAndSpriteFrame('/assets/home', 'home')
            if (close) {
                this.showLoading()
            }

            data.blueLeadAssets = await loadJosnAndSpriteFrame('/assets/blueLead', 'blueLead')
            data.greenLeadAssets = await loadJosnAndSpriteFrame('/assets/greenLead', 'greenLead')
            data.mapAssets = await loadJosnAndSpriteFrame('/assets/map', 'map')
            data.enemyAssets = await loadJosnAndSpriteFrame("/assets/npc", 'enemy')
            data.font.length == 0 ? data.font = await resource.loadDir('/fonts/', Font) : ""
            data.audio.length == 0 ? data.audio = await resource.loadDir('/audio/', AudioClip) : ""
            if (close) {
                await this.hideLoading()
            }
            resolve()
        })
    }
    getAssetsLength() {
        let loading = false
        if (DataManager.Instance.blueLeadAssets.jsonAsset.length == 0) {
            loading = true
        }
        if (DataManager.Instance.greenLeadAssets.jsonAsset.length == 0) {
            loading = true
        }
        if (DataManager.Instance.homeAssets.jsonAsset.length == 0) {
            loading = true
        }
        if (DataManager.Instance.mapAssets.jsonAsset.length == 0) {
            loading = true
        }
        if (DataManager.Instance.enemyAssets.jsonAsset.length == 0) {
            loading = true
        }
        if (DataManager.Instance.audio.length == 0) {
            loading = true
        }
        if (DataManager.Instance.font.length == 0) {
            loading = true
        }
        return loading
    }
    async showDrawerText({ name = "tips", label = "提示", text }) {
        let { content } = await this.showDrawerContent({ name, tips: label })
        const helpNode = createUINode()
        helpNode.setParent(content)
        createUILabel({ parentNode: helpNode, text, lineHeight: 50 })
    }
    async hideLoading() {
        await this.close('loading')
    }
    async showLoading(text: string = "loading") {
        let { content } = await this.showDrawerContent({ name: "loading", tips: text, showCancle: false })
        if (!content.isValid) return
        const loadingNode = createUINode("loadingNode")
        loadingNode.setParent(content)
        loadingNode.setScale(2, 2)
        const sprite = loadingNode.addComponent(Sprite)
        let spriteList = DataManager.Instance.homeAssets.jsonAsset.filter(item => item.filename.includes(`loading`))
        let spriteFrame = getFrameAllAsset(DataManager.Instance.homeAssets, spriteList)
        sprite.spriteFrame = spriteFrame[0]
        sprite.sizeMode = Sprite.SizeMode.CUSTOM
        let clip = setListTrantion(spriteFrame, "loading")
        const animation = sprite.addComponent(Animation)
        animation.defaultClip = clip
        animation.play()
    }
    async closeMiniLoading() {
        if (this.openDrawerName) {
            this.parentNode.getChildByName(this.openDrawerName).setPosition(0, 0,)
        }
        await this.close('miniLoading')
    }
    // 小的加载遮罩
    async showMiniLoading({tips}) {
        return new Promise<Boolean>((resolve, reject) => {
            if (typeof (wx) !== "undefined") {
                wx.showModal({
                    title: '提示',
                    content: tips,
                    async success(res) {
                        if (res.confirm) {
                            resolve(true)
                        } else if (res.cancel) {
                            console.log('用户点击取消')
                            reject(false)
                        }
                    }
                })
            }else{
                resolve(true)
            }
        })
    }
    // // 小的加载遮罩
    // async showMiniLoading({
    //     tips = "",
    //     cancel_target = this.node,
    //     cancel_text = "",
    //     cancel_data = "",
    //     cancel_component = "ControllerManager",
    //     cancel_handler = "closeMiniLoading",
    //     confirm_text = "",
    //     confirm_data = "",
    //     confirm_target,
    //     confirm_component = "",
    //     confirm_handler = ""
    // }) {
    //     let drawerNode = createUINode("miniLoading")
    //     drawerNode.setSiblingIndex(9)
    //     drawerNode.setParent(this.node)
    //     if (this.openDrawerName) {
    //         this.parentNode.getChildByName(this.openDrawerName).setPosition(0, -1200,)
    //     }
    //     return new Promise<{ drawerNode, maskBox }>(async (resolve, reject) => {
    //         // 遮罩的框
    //         const maskBox = createUINode(`maskBox`)
    //         maskBox.setParent(drawerNode)
    //         const widget = maskBox.addComponent(Widget)
    //         widget.isAlignHorizontalCenter = true
    //         const boxSprite = maskBox.addComponent(Sprite)
    //         boxSprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, `confirm.png`).spriteFrame
    //         boxSprite.sizeMode = Sprite.SizeMode.CUSTOM
    //         const transform = maskBox.addComponent(UITransform)
    //         transform.setContentSize(350 * 2, 220 * 2)
    //         maskBox.setPosition(0, -300)
    //         // 顶部提示
    //         const tipNode = createUINode("tipNode")
    //         tipNode.setParent(maskBox)
    //         createUILabel({ parentNode: tipNode, text: tips })
    //         const tipWidget = tipNode.addComponent(Widget)
    //         tipWidget.isAlignTop = true
    //         tipWidget.top = 90
    //         tipWidget.isAlignHorizontalCenter = true

    //         const confirmNode = createUINode("revertNode")
    //         confirmNode.setParent(maskBox)
    //         const button = confirmNode.addComponent(Button)
    //         const confirmHandler = new EventHandler();
    //         confirmHandler.target = confirm_target; // 这个 node 节点是你的事件处理代码组件所属的节点
    //         confirmHandler.component = confirm_component;// 这个是脚本类名
    //         confirmHandler.handler = confirm_handler;
    //         confirmHandler.customEventData = confirm_data;
    //         button.duration = .1
    //         button.zoomScale = 0.95
    //         button.transition = Button.Transition.SCALE
    //         button.clickEvents.push(confirmHandler)
    //         createUILabel({ parentNode: confirmNode, text: confirm_text })
    //         const revertWidget = confirmNode.addComponent(Widget)
    //         revertWidget.isAlignBottom = true
    //         revertWidget.bottom = 90
    //         if (cancel_text != '') {
    //             revertWidget.isAlignRight = true
    //             revertWidget.right = 120
    //         } else {
    //             revertWidget.isAlignHorizontalCenter = true
    //         }

    //         if (cancel_text != '') {
    //             const cancelNode = createUINode("cancelNode")
    //             cancelNode.setParent(maskBox)
    //             const cancelButton = cancelNode.addComponent(Button)
    //             const cancelHandler = new EventHandler();
    //             cancelHandler.target = cancel_target; // 这个 node 节点是你的事件处理代码组件所属的节点
    //             cancelHandler.component = cancel_component;// 这个是脚本类名
    //             cancelHandler.handler = cancel_handler;
    //             cancelHandler.customEventData = cancel_data;
    //             cancelButton.duration = .1
    //             cancelButton.zoomScale = 0.95
    //             cancelButton.transition = Button.Transition.SCALE
    //             cancelButton.clickEvents.push(cancelHandler)
    //             createUILabel({ parentNode: cancelNode, text: cancel_text })
    //             const cancelWidget = cancelNode.addComponent(Widget)
    //             cancelWidget.isAlignBottom = true
    //             cancelWidget.bottom =90
    //             cancelWidget.isAlignLeft = true
    //             cancelWidget.left = 120
    //         }


    //         DataManager.Instance.drawerNumber = DataManager.Instance.drawerNumber + 1
    //         tween(maskBox)
    //             .by(.2, { position: new Vec3(0, 300, 0) })
    //             .call(() => {
    //                 resolve({ drawerNode, maskBox })
    //             })
    //             .start()

    //     })
    // }
    // 展示模态框的整体
    async showDrawerContent({ name = "", tips = "提 示", showCancle = true, cancleText = "返 回", node = null, sprite_frame = 1204 }) {
        return new Promise<{ drawerNode, content, maskBox }>(async (resolve, reject) => {
            this.openDrawerName = name
            let drawerNode = createUINode(`${name}`)
            drawerNode.setSiblingIndex(9)
            let parentNode = node ? node : this.node
            this.parentNode = parentNode
            drawerNode.addComponent(UIOpacity)
            drawerNode.setParent(parentNode)
            // 遮罩的框
            const maskBox = createUINode(`maskBox`)
            maskBox.setParent(drawerNode)
            const widget = maskBox.addComponent(Widget)
            widget.isAlignHorizontalCenter = true
            const boxSprite = maskBox.addComponent(Sprite)
            boxSprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, `${sprite_frame}.png`).spriteFrame // DataManager.Instance.commonAssets.find(item => item.name == '1204')
            boxSprite.sizeMode = Sprite.SizeMode.CUSTOM
            const transform = maskBox.addComponent(UITransform)
            transform.setContentSize(452 * 2, 354 * 2)
            maskBox.setPosition(0, -300)

            const content = createUINode(`pauseMaskContent`)
            content.setParent(maskBox)
            const contentTransform = content.getComponent(UITransform)
            contentTransform.setContentSize(452 * 2 - 60, 354 * 2 - 150)
            content.setPosition(0, 10)
            const contentSprite = content.addComponent(Sprite)
            contentSprite.sizeMode = Sprite.SizeMode.CUSTOM
            // 顶部提示
            const tipNode = createUINode("tipNode")
            tipNode.setParent(maskBox)
            createUILabel({ parentNode: tipNode, text: tips })
            const tipWidget = tipNode.addComponent(Widget)
            tipWidget.isAlignTop = true
            tipWidget.top = 0
            tipWidget.isAlignHorizontalCenter = true
            // 返回按钮
            if (showCancle) {
                const revertNode = createUINode("revertNode")
                revertNode.setParent(maskBox)
                const button = revertNode.addComponent(Button)
                const clickEventHandler = new ControllerManager.EventHandler();
                clickEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
                clickEventHandler.component = 'ControllerManager';// 这个是脚本类名
                clickEventHandler.handler = 'closeDrawer';
                clickEventHandler.customEventData = name;
                button.duration = .1
                button.zoomScale = 0.95
                button.transition = Button.Transition.SCALE
                button.clickEvents.push(clickEventHandler)
                createUILabel({ parentNode: revertNode, text: cancleText })
                const revertWidget = revertNode.addComponent(Widget)
                revertWidget.isAlignBottom = true
                revertWidget.bottom = 30
                revertWidget.isAlignHorizontalCenter = true
            }
            DataManager.Instance.drawerNumber = DataManager.Instance.drawerNumber + 1
            tween(maskBox)
                .by(.2, { position: new Vec3(0, 300, 0) })
                .call(() => {
                    resolve({ drawerNode, content, maskBox })
                })
                .start()

        })

    }
}


